package com.rpoonolly.simplegame.worldGrid;

import java.awt.image.BufferedImage;
import java.util.Collections;
import java.util.List;

import com.rpoonolly.simplegame.Config;
import com.rpoonolly.simplegame.core.aabb.AABBEntity;
import com.rpoonolly.simplegame.renderer.SimpleSwingRenderer;
import com.rpoonolly.simplegame.textures.TextureId;
import com.rpoonolly.simplegame.textures.TextureLoader;

public class WorldGridRenderer extends SimpleSwingRenderer {
	protected WorldGrid worldGrid;
	private AABBEntity player;
	protected AABBEntity camera;
	private TextureLoader textureLoader;
	
	public WorldGridRenderer(WorldGridGameMap gameMap, AABBEntity player, TextureLoader textureLoader) {
		this.textureLoader = textureLoader;
		this.worldGrid = gameMap.getGrid();
		this.player = player;
		this.camera = new AABBEntity();
	}

	@Override
	public void render() {
		clearScreen();
		setFocalPoint(player);
		
		List<WorldGridTile> tilesToRender = worldGrid.getCollidingTiles(camera);
		for(WorldGridTile tile : tilesToRender)
			renderTile(tile);
	}
	
	@Override
	public void setFocalPoint(AABBEntity focus) {
		super.setFocalPoint(focus);
		
		camera.setX((int) (focalPoint.x - (windowWidth / 2)));
		camera.setY((int) (focalPoint.y - (windowHeight / 2)));
		camera.setWidth((int) windowWidth);
		camera.setHeight((int) windowHeight);
	}
	
	private void renderTile(WorldGridTile tile) {
		List<TextureId> tileTextures = tile.getTextures();
		GridCoordinate tileCoord = tile.getCoordinate();
		
		if (tileTextures == null)
			tileTextures = Collections.singletonList(Config.WORLD_GRID_TEXTURE_DEFAULT);
		
		for(TextureId texture : tileTextures) {
			renderTextureTile(
					texture, 
					tileCoord.getX() * worldGrid.getGridCellWidth(),
					tileCoord.getY() * worldGrid.getGridCellHeight(),
					worldGrid.getGridCellWidth(),
					worldGrid.getGridCellHeight()
				);
		}
	}
	
	protected void renderTextureTile(TextureId textureTile, int x, int y, int width, int height) {
		double xcoord, ycoord;
		xcoord = x - camera.getX();
		ycoord = -1 * ((y + height) - (camera.getY() + camera.getHeight()));
		
		if (xcoord + width < 0 || ycoord + height < 0
				|| xcoord > windowWidth || ycoord > windowHeight)
			return;
		
		BufferedImage texture = textureLoader.loadTexture(textureTile);
		graphics.drawImage(texture, (int) xcoord, (int) ycoord, width, height, null);
	}
}
